package com.roc.web.action.dailiReport;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionContext;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.MerchantReport;
import com.roc.pojo.Operators;
import com.roc.pojo.OrgBean;
import com.roc.service.IExcelService;
import com.roc.service.IPagenitionService;
import com.roc.service.IorgService;
import com.roc.service.ServiceException;
import com.roc.util.Constance;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.web.action.susMerinfo.SusMerinfoSearchCondition;

@Component
@Scope("prototype")
@Namespace("/dailiReport")
public class DailiReportAction extends PaginationBaseAction {
	
	private Logger logger=LogManager.getLogger(DailiReportAction.class);
	
	private DailiReportSearchCondition searchCondition;
	private InputStream excelFile;
	private String  excelName;
	private File upload;
	private List<OrgBean> orgList=new ArrayList<OrgBean>();
	
	@Autowired
	IPagenitionService pagenitionService;
	@Autowired
	IExcelService excelService;
	@Autowired
	IorgService orgService;
	
	@Action(value = "init", results = { @Result(name = "success", location = "/pages/daiLiReport/daiLiQuery.jsp")
    })
	public String init(){
		Operators loginOperators = (Operators) ActionContext.getContext().getSession().get(Constant.SESSION_LOGIN_MERCHANT);
	    try{
			orgList=orgService.listOrgs(loginOperators);
			
		}catch (Exception e) {
		// TODO: handle exception
		addActionError("加载信息失败，请联系客服人员");
		logger.error(e.getMessage(),e);
		}
		return SUCCESS;
	}
	
	@Action(value = "query", 
			results = { @Result(name = "success", location = "/pages/daiLiReport/daiLiQuery.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String query(){
		
		if(searchCondition==null){
			searchCondition=(DailiReportSearchCondition)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new DailiReportSearchCondition();
			}
		}
		
		try {
			
			init();
			if(Constance.Null2EmptyTrim(searchCondition.getStartDate()).equals("")||Constance.Null2EmptyTrim(searchCondition.getEndDate()).equals("")){
				getRequest().setAttribute("msg", "请选择时间");
				
				return SUCCESS;
				
			}
			int rows=pagenitionService.count(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAll(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
				
			}
			List<MerchantReport> merList=dealWidth(searchRsList);
			
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute("merList", merList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
			
		}catch(ServiceException e){
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
		}
		
		return SUCCESS;
	}
	
	@Action(value="dailiExport",results = {@Result(name="success",type="stream"
			,params = { "contentType", "application/vnd.ms-excel", "inputName",  
			            "excelFile","contentDisposition",  "attachment;filename=${excelName}.xls",
			            "bufferSize", "1024*3" }),@Result(name="error",location="/pages/daiLiReport/query.jsp") }) 
	public String dailiExport() throws IOException{
		
		if(searchCondition==null){
			searchCondition=(DailiReportSearchCondition)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new DailiReportSearchCondition();
			}
		}
		
		try {
			
			init();
			if(Constance.Null2EmptyTrim(searchCondition.getStartDate()).equals("")||Constance.Null2EmptyTrim(searchCondition.getEndDate()).equals("")){
				getRequest().setAttribute("msg", "请选择时间");
				
				return SUCCESS;
				
			}
			int rows=pagenitionService.count(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAll(searchCondition, calcuStart(getCurrentPage()), rows);
				
			}
			List<MerchantReport> merList=dealWidth(searchRsList);
			
			HSSFWorkbook work=excelService.daiLIExcel(merList, searchCondition.getStartDate(), searchCondition.getEndDate());
			 ByteArrayOutputStream output = new ByteArrayOutputStream();  
			         work.write(output);  
			   
			        byte[] ba = output.toByteArray();  
			         excelFile = new ByteArrayInputStream(ba);  
			         output.flush();  
			         output.close();  
			
			
		}catch(ServiceException e){
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
		}
		
			
		return SUCCESS;
	}
	
	public String getExcelName() {
		String excelName="代理商交易统计报表"+Constance.formateDate();
		 
			try {
				excelName = new String(excelName.getBytes(),"ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				logger.info("生成excel名称失败了！");
			}
		 
		return  excelName;
		
	}
	
	
	private List<MerchantReport> dealWidth(List<Object> list){
		List<MerchantReport> merList=new ArrayList<MerchantReport>();
		
        if(list.size()>0 && list!=null){
			
			Iterator iterator=list.iterator();
			while (iterator.hasNext()) {
				Object[] obj= (Object[])iterator.next();
				MerchantReport mer=new MerchantReport();
				mer.setAccountNo(Constance.Null2EmptyTrim(obj[0]));
				mer.setRealName(Constance.Null2EmptyTrim(obj[1]));
				mer.setOrgCode(Constance.Null2EmptyTrim(obj[2]));
				for(int i=0;i<orgList.size();i++){
					if(orgList.get(i).getOrg_code().endsWith(mer.getOrgCode())){
						mer.setOrgCode(orgList.get(i).getOrg_name());
						break;
					}
				}
				mer.setMccType(Constance.Null2EmptyTrim(obj[3]));
				mer.setTotalFee((Double.parseDouble(Constance.null2Amt(obj[4]))));
				mer.setTotalAmt((Double.parseDouble(Constance.null2Amt(obj[5]))));
				mer.setTotalNum(Long.parseLong(Constance.Null2EmptyTrim(obj[6])));
				mer.setTransDate(Constance.Null2EmptyTrim(obj[7]));
				merList.add(mer);
			}
        }
		
		return merList;
		
	}
	
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return this.searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		// TODO Auto-generated method stub
		this.searchCondition=(DailiReportSearchCondition) searchCondition;
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		// TODO Auto-generated method stub
		getSession().setAttribute(SEARCH_SESSION_MERCHANT_REPORT, searchCondition);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (BaseSearchCondition) getSession().getAttribute(SEARCH_SESSION_MERCHANT_REPORT);
	}

	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return null;
	}

	public DailiReportSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(DailiReportSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public void setExcelName(String excelName) {
		this.excelName = excelName;
	}

	public List<OrgBean> getOrgList() {
		return orgList;
	}

	public void setOrgList(List<OrgBean> orgList) {
		this.orgList = orgList;
	}
	
	

}
